package com.rk.kbk.controller;

import com.rk.kbk.common.*;
import com.rk.kbk.controller.util.PayUtils;
import com.rk.kbk.controller.util.PayUtilsRide;
import com.rk.kbk.dao.*;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.*;
import com.rk.kbk.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @OrderGoodsController
 * @订单详情Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/orderGoods")
public class OrderGoodsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private CashRecordDao cashRecordDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsUnitDao goodsUnitDao;
    @Autowired
    private AreaDetailDao areaDetailDao;
    @Autowired
    private OpenAreaDao openAreaDao;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SqlToResult sqlToResult;
    public static String wxnotify = "/api/payOver/wxpay/goodsOrderSuccess";
    /**
     * @添加/修改订单详情
     * @param orderGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateOrderGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateOrderGoods(@RequestBody OrderGoods orderGoods){
        log.debug("添加/修改订单详情");
        orderGoodsDao.save(orderGoods);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改订单详情
     * @param orderGoodss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeOrderGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeOrderGoods(@RequestBody List<OrderGoods> orderGoodss){
        log.debug("批量添加/修改订单详情");
        orderGoodsDao.save(orderGoodss);
        return JsonResp.ok();
    }

    /**
     * @获取订单详情详情-ByOrderGoodsId
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/orderGoodsDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOrderGoodsDetailsByOrderGoodsId(Long orderGoodsId,Integer type) {
        log.debug("获取订单详情详情-ByOrderGoodsId");
        Map map=new HashMap();
        OrderGoods orderGoods = orderGoodsDao.findOne(orderGoodsId);
        Goods goods=orderGoods.getGoods();
        GoodsUnit goodsUnit=orderGoods.getGoodsUn();
        User user = orderGoods.getUser();
        Long addressId = user.getAddress();
        Address address = addressDao.findOne(addressId);
        map.put("title",goods.getTitle());
        map.put("goodsUrl",goods.getGoodsUrl());
        map.put("goodsType",goods.getGoodsType());
        map.put("realName",user.getRealName());
        map.put("phone",user.getPhone());
        map.put("num",orderGoods.getNums());
        map.put("unitStandard",goodsUnit.getUnitStandard());
        map.put("marketPrice",goodsUnit.getMarketPrice());
        map.put("unitPrice",goodsUnit.getUnitPrice());
        map.put("orderNumber",orderGoods.getOrderNumber());
        map.put("orderStatus",orderGoods.getOrderStatus());
        Date payTime=orderGoods.getPayTime();
        if(payTime!=null){
            map.put("payTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderGoods.getPayTime()));
        }else {
            map.put("payTime",orderGoods.getPayTime());
        }
       Date gmtDatetime=orderGoods.getGmtDatetime();
        map.put("gmtDatetime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(gmtDatetime));
        Date comcateTime=orderGoods.getComcateTime();
        if(comcateTime!=null){
            map.put("comcateTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(comcateTime));//完成时间
        }else {
            map.put("comcateTime",comcateTime);
        }
        if(type==1){ //商家地址
            map.put("province",address.getProvince());
            map.put("city",address.getCity());
            map.put("county",address.getCounty());
            map.put("addressDetail",address.getAddressDetail());
        }else if(type==2){//骑手自提地址
            OpenArea openArea=openAreaDao.findByAreaCode(address.getAreaCode());
            AreaDetail areaDetail=areaDetailDao.findByAreaCode(address.getAreaCode());
            map.put("province",openArea.getProvince());
            map.put("city",openArea.getCity());
            map.put("county",openArea.getArea());
            map.put("addressDetail",areaDetail.getDetailPlace());
        }
        return JsonResp.ok(map);
    }



    /**
     * @购买商品（提交订单）
     * @param orderGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/saveCheckedGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveCheckedGoods(@RequestBody OrderGoods orderGoods) {
        log.debug("购买商品（提交订单）");
        User user=userDao.findOne(orderGoods.getUser().getId());
        Goods goods=goodsDao.findOne(orderGoods.getGoods().getId());
        GoodsUnit goodsUnit=goodsUnitDao.findOne(orderGoods.getGoodsUn().getId());
        orderGoods.setUser(user);
        orderGoods.setGoods(goods);
        orderGoods.setGoodsUn(goodsUnit);
        orderGoods.setOrderStatus(1);//已提交未支付
        String order_number= OrderUtils.getGoodsOrderNo();
        orderGoods.setOrderNumber(order_number);
        orderGoodsDao.save(orderGoods);
        Map map =new HashMap();
        map.put("orderGoodsId",orderGoods.getId());
        map.put("orderNumber",order_number);
        map.put("money",orderGoods.getPayMoney());
        map.put("num",orderGoods.getNums());
        return JsonResp.ok(map);
    }

    /**
     * @提交订单页面数据显示
     * @areaCode 骑手的注册地址区域代码
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/submitPageOrderDate",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp submitPageOrderDate(Long goodsOrderId) {
        log.debug("提交订单页面数据显示");
        OrderGoods orderGoods=orderGoodsDao.findOne(goodsOrderId);
        User user=orderGoods.getUser();
        Address address=addressDao.findOne(user.getAddress());
        AreaDetail areaDetail=areaDetailDao.findByAreaCode(address.getAreaCode());
        OpenArea openArea=openAreaDao.findByAreaCode(address.getAreaCode());
        areaDetail.setOpenArea(openArea);
        return JsonResp.ok(areaDetail);
    }



    /**
     * @提交订单
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/submitOrderGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp submitOrderGoods(Long orderGoodsId) {
        log.debug("提交订单");
        OrderGoods orderGoods=orderGoodsDao.findOne(orderGoodsId);
        orderGoods.setOrderStatus(1);//1表示提交未支付
        orderGoodsDao.save(orderGoods);
        return JsonResp.ok();
    }


    /**
     * @支付订单
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/paymentOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp paymentOrder(Long orderGoodsId, Integer type, HttpServletRequest request) {
        log.debug("支付订单");
        OrderGoods orderGoods=orderGoodsDao.findOne(orderGoodsId);
        User user=orderGoods.getUser();
        Integer userType=user.getUserType();
        Double payMoney=orderGoods.getPayMoney();
        String title="";
         if(type==1){//余额支付
             Account account=accountDao.findByUser(user);
             Double allMoney=account.getAllMoney();
             if(new BigDecimal(String.valueOf(allMoney)).compareTo(new BigDecimal(String.valueOf(payMoney)))<0){
                 orderGoods.setOrderStatus(2);
                 orderGoodsDao.save(orderGoods);
                 return JsonResp.fa("账户余额不足!");
             }else {
                 Double leftMoney=new BigDecimal(String.valueOf(allMoney)).subtract(new BigDecimal(String.valueOf(payMoney))).doubleValue();
                 account.setAllMoney(leftMoney);
                 accountDao.save(account);
                 orderGoods.setPayType(String.valueOf(type));
                 orderGoods.setPayTime(new Date());
                 orderGoods.setOrderStatus(3);
                 orderGoodsDao.save(orderGoods);
                 /********************************消费记录***********************************/
                 title="商城订单付款金额"+payMoney+"元(余额)";
                 //消费记录
                 CashRecord cashRecord =new CashRecord();
                 cashRecord.setUser(user);
                 cashRecord.setTitle(title);
                 cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());
                 cashRecord.setOrderType(2);
                 cashRecord.setOrderNumber(orderGoods.getOrderNumber());
                 cashRecord.setRecoedType(3);
                 if(type==1){
                     cashRecord.setMoneyType(1);
                 }
                 cashRecord.setMoney(-orderGoods.getPayMoney());
                 if(userType==2){
                     cashRecord.setGivePerson(2);
                 }else if(userType==3){
                     cashRecord.setGivePerson(1);
                 }
                 cashRecord.setPayType(1);
                 cashRecord.setStatus(1);
                 cashRecord.setReceivePerson(0);
                 cashRecordDao.save(cashRecord);
             }
         }else if(type==3){//微信支付方式
             String sym = request.getRequestURL().toString().split("/api/")[0];
             String trade_no = (orderGoods.getId()+ "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
             Map map=null;
//             String json=null;
             if(userType==2){//骑手微信支付
                 map = PayUtilsRide.WxPay(trade_no, payMoney, "支付", sym + wxnotify);
             }else if(userType==3){//商户微信支付
                 map = PayUtils.WxPay(trade_no, payMoney, "支付", sym + wxnotify);
             }
             if (map != null) {
                 orderGoods.setPayType(String.valueOf(type));
                 orderGoods.setPayTime(new Date());
                 orderGoods.setOrderStatus(3);
                 orderGoodsDao.save(orderGoods);
                 return JsonResp.ok("成功", map);
             }else{
                 throw new FailException();
             }


         }

        return JsonResp.ok(orderGoods);
    }




    /**
     * @支付订单 (点击确认支付)
     * @param orderGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/paymentOrderUnderClickOk",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp paymentOrderUnderClickOk(@RequestBody OrderGoods orderGoods) {
        log.debug("支付订单 (点击确认支付)");
        Long loginUserId = userService.currentUserId();//获取当前登录着
        if(loginUserId!=null  && loginUserId.equals(orderGoods.getId())){
            //如果用余额支付
            if("1".equals(orderGoods.getPayType())){
                OrderGoods one=orderGoodsDao.findOne(orderGoods.getId());
                User user=one.getUser();
                Account account=accountDao.findByUser(user);
                Double allMoney=account.getAllMoney();

                if(allMoney.compareTo(orderGoods.getPayMoney())<0){//账户余额不足
                    return JsonResp.ok("账户余额不足");
                }else {
                    BigDecimal b1 = new BigDecimal(allMoney.toString());
                    BigDecimal b2 = new BigDecimal(orderGoods.getPayMoney().toString());
                    Double saveMoney=b1.subtract(b2).doubleValue();
                    account.setAllMoney(saveMoney);
                    accountDao.save(account);
                    one.setPayTime(new Date());
                    orderGoodsDao.save(one);
                    return JsonResp.ok(orderGoods.getId());
                }

            }else{ //其他支付方式支付

            }
            return JsonResp.ok("支付成功");
        }else {
            return JsonResp.ok("身份信息验证出错！");
        }
    }
    /**
     * @param pageNum    第几页
     * @param pageSize   每页的条数
     * @return 返回值JsonResp
     * @获取商城订单列表 (后台使用)
     */
    @RequestMapping(value = "/getOrderGoodsUserByHouTai",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp CashRecordList(Integer usertype,String orderNumber,Integer pageNum, Integer pageSize) {
        log.debug("获取商城订单列表 (后台使用)");
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page page = orderGoodsDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    if (StringUtils.isNotBlank(orderNumber)) {
                        expressions.add(cb.like(root.get("orderNumber"), "%"+ orderNumber +"%"));
                    }
                    if(usertype!=0){
                            List<User> userList=userDao.findByUserTypeAndUserStatus(usertype,1);
                            CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                            for (User l : userList) {
                                expressions.add(stick.value(l));
                            }
                    }

                    return predicate;
                }, pageable);

        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @支付完成
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/paymentOrderOver",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp paymentOrderOver(Long orderGoodsId) {
        log.debug("支付完成");
        OrderGoods orderGoods=orderGoodsDao.findOne(orderGoodsId);
        Map map =new HashMap<>();
        map.put("orderNumber",orderGoods.getOrderNumber());
        map.put("payMoney",orderGoods.getPayMoney());
        map.put("id",orderGoodsId);
        map.put("payYype",orderGoods.getPayType());
        map.put("payTime",orderGoods.getPayTime());
        return JsonResp.ok(map);
    }


    /**
     * @我的订单
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findAllCommList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAllCommList(Long userId,Integer pageNum, Integer pageSize) {
        log.debug("我的订单-订单列表");
      /*   List<Integer> orderStatusList=new ArrayList<>();
        orderStatusList.add(0);//表示未提交订单
        orderStatusList.add(1);//表示提交未支付
        orderStatusList.add(3);//表示支付成功
        orderStatusList.add(4);//已发货
    List<OrderGoods> orderGoodsList=orderGoodsDao.findByUserAndOrderStatusIn(user,orderStatusList);
        List<Map> orderGoodsMapList=new ArrayList<>();
        for(int i=0,y=orderGoodsList.size();i<y;i++){
            Map map =new HashMap();
            OrderGoods orderGoods=orderGoodsList.get(i);
            Goods goods=orderGoods.getGoods();
            GoodsUnit goodsUnit=orderGoods.getGoodsUn();
            map.put("orderNumber",orderGoods.getOrderNumber());
            map.put("payMoney",orderGoods.getPayMoney());
            map.put("orderGoodsId",orderGoods.getId());
            map.put("nums",orderGoods.getNums());
            map.put("payYype",orderGoods.getPayType());
            map.put("title",goods.getTitle());
            map.put("goodUrl",goods.getGoodsUrl());
            map.put("goodsId",goods.getId());
            map.put("orderStatus",orderGoods.getOrderStatus());
            map.put("unitPrice",goodsUnit.getUnitPrice());
            map.put("unitStandard",goodsUnit.getUnitStandard());
            map.put("goodsUnitId",goodsUnit.getId());
            orderGoodsMapList.add(map);
        }*/
        User user=userDao.findOne(userId);
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page page = orderGoodsDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                        expressions.add(cb.equal(root.get("user"), user));
                        CriteriaBuilder.In<Object> stick = cb.in(root.get("orderStatus"));
                            expressions.add(stick.value(0));//表示未提交订单
                            expressions.add(stick.value(1));//表示提交未支付
                            expressions.add(stick.value(3));//表示支付成功
                            expressions.add(stick.value(4));//已发货
                    return predicate;
                }, pageable);

        List<OrderGoods> orderGoodsList=page.getContent();
        List<Map> orderGoodsMapList=new ArrayList<>();
        for(int i=0,y=orderGoodsList.size();i<y;i++){
            Map map =new HashMap();
            OrderGoods orderGoods=orderGoodsList.get(i);
            Goods goods=orderGoods.getGoods();
            GoodsUnit goodsUnit=orderGoods.getGoodsUn();
            map.put("orderNumber",orderGoods.getOrderNumber());
            map.put("payMoney",orderGoods.getPayMoney());
            map.put("orderGoodsId",orderGoods.getId());
            map.put("nums",orderGoods.getNums());
            map.put("payYype",orderGoods.getPayType());
            map.put("title",goods.getTitle());
            map.put("goodUrl",goods.getGoodsUrl());
            map.put("goodsId",goods.getId());
            map.put("orderStatus",orderGoods.getOrderStatus());
            map.put("unitPrice",goodsUnit.getUnitPrice());
            map.put("unitStandard",goodsUnit.getUnitStandard());
            map.put("goodsUnitId",goodsUnit.getId());
            orderGoodsMapList.add(map);
        }
        Map map =new HashMap();
        map.put("list",orderGoodsMapList);
        map.put("total",page.getTotalElements());
        map.put("pages",page.getTotalPages());


        return JsonResp.ok(map);
    }


    /**
     * @我的订单 (详情)
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findOneCommDetail",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOneCommDetail(Long orderGoodsId,int orderStatus) {
        log.debug("我的订单-（待付款、待收货、已完成）订单详情");
       OrderGoods orderGoods=orderGoodsDao.findByIdAndOrderStatus(orderGoodsId,orderStatus);
        GoodsUnit goodsUnit=orderGoods.getGoodsUn();
        Goods goods=orderGoods.getGoods();
        User user=orderGoods.getUser();
        Map map =new HashMap();
        map.put("orderNumber",orderGoods.getOrderNumber());
        map.put("payMoney",orderGoods.getPayMoney());
        map.put("orderGoodsId",orderGoods.getId());
        map.put("nums",orderGoods.getNums());
        map.put("gmtDatetime",orderGoods.getGmtDatetime());
        map.put("payTime",orderGoods.getPayTime());
        map.put("comcateTime",orderGoods.getComcateTime());
        map.put("unitStandard",goodsUnit.getUnitStandard());
        map.put("unitPrice",goodsUnit.getUnitPrice());
        map.put("title",goods.getTitle());
        map.put("goodUrl",goods.getGoodsUrl());
        map.put("phone",user.getPhone());
        map.put("sex",user.getSex());
        map.put("realName",user.getRealName());
        return JsonResp.ok(map);
    }
    /**
     * @分页查询订单详情(jpa方式)
     * @param orderGoods 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderGoodsJpa(@RequestBody(required = false) OrderGoods orderGoods, Integer pageNum, Integer pageSize) {
        log.debug("分页查询订单详情(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == orderGoods) {
            page = orderGoodsDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  orderGoods.getUserName();
            page = orderGoodsDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<OrderGoods> content = page.getContent();
//        for (OrderGoods orderGoods1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }



    /**
     * @删除订单详情-one(永久)
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteOrderGoodsOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteOrderGoodsOne(Long orderGoodsId) {
        log.debug("删除订单详情-one(永久)");
        orderGoodsDao.delete(orderGoodsId);
        return JsonResp.ok();
    }



    /**
     * @更新订单状态（后台发货）
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sendGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp sendGoods(Long orderGoodsId) {
        log.debug("更新订单状态（后台发货）");
        OrderGoods orderGoods=orderGoodsDao.findByIdAndOrderStatus(orderGoodsId,3);//3代表支付成功
        orderGoods.setOrderStatus(4);//更改为已发货
        orderGoods.setComcateTime(new Date());//完成时间
        orderGoodsDao.save(orderGoods);
        return JsonResp.ok();
    }

    /**
     * @删除订单（后台）
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteOrderGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp delete(Long orderGoodsId) {
        log.debug("删除订单详情-one(永久)");
        orderGoodsDao.delete(orderGoodsId);
        //删除该商品对应的规格

        return JsonResp.ok();
    }

    /**
     * @批量删除订单详情(永久)
     * @param orderGoodss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeOrderGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeOrderGoods(@RequestBody List<OrderGoods> orderGoodss) {
        log.debug("批量删除订单详情(永久)");
        orderGoodsDao.delete(orderGoodss);
        return JsonResp.ok();
    }

    /**
     * @分页查询用户商品订单详情(jpa方式)
     * @param userId 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/pageByUser",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderGoodsJpaByUserId(Long userId,Integer pageNum,Integer pageSize) {
        log.debug("分页查询用户商品订单详情(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == userId) {
        }else{
            page = orderGoodsDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        User user = userDao.findOne(userId);
                        if(user!=null) {
                            expressions.add(cb.equal(root.get("user"), user));
                        }
                            return predicate;
                    }, pageable);
        }
        return JsonResp.ok(new PageDto(page));
    }


    /**
     * @取消订单（骑手和商家）
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/cancelOrderGoods",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp cancelOrderGoods(Long orderGoodsId) {
        log.debug("取消订单（骑手和商家）");
       OrderGoods orderGoods =orderGoodsDao.findOne(orderGoodsId);
        orderGoods.setOrderStatus(5);//5代表订单取消
        orderGoodsDao.save(orderGoods);
        return JsonResp.ok();
    }

    /**
     * @删除订单（骑手和商家）
     * @param orderGoodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/hiddenOrderGoods",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp hiddenOrderGoods(Long orderGoodsId) {
        log.debug("取消订单（骑手和商家）");
        OrderGoods orderGoods =orderGoodsDao.findOne(orderGoodsId);
        orderGoods.setOrderStatus(6);//5代表订单取消
        orderGoodsDao.save(orderGoods);
        return JsonResp.ok();
    }

    /**
     * @return 返回值JsonResp
     * @装备数量
     */
    @RequestMapping(value = "/equipmentSum",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp equipmentSum(Long userId) {
        log.debug("装备数量");
        String sql=" SELECT count(user) as sum FROM `order_goods` WHERE `user`= "+userId +" and order_status=7 ";
        Object resultList = sqlToResult.getResultList(sql, "one");
        Map map = PubLib.copyObject(resultList, Map.class);
        return JsonResp.ok(map);

    }

}
